<template>
  <div>
    <el-card class="box-card">
      <!-- 添加 -->
      <div slot="header" class="clearfix">
        <el-button icon="el-icon-plus" type="primary" size="small" @click="isDialog">添加</el-button>
      </div>
      <!-- 表格数据 -->
      <el-table :data="trademarkList" border style="width: 100%">
        <el-table-column label="序号" type="index" width="80" />
        <el-table-column prop="tmName" label="品牌名称" />
        <el-table-column label="品牌LOGO">
          <template #default="{row}">
            <el-image :src="row.logoUrl" style="width: 160px;height: 100px"></el-image>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280">
          <template #default="{row}">
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-edit-outline"
              @click="upDataTrademarkItem(row)"
              >修改</el-button>
            <el-popconfirm
              title="确定删除吗？"
              @onConfirm="removeTrademarkItem(row.id)"
            >
              <el-button
                slot="reference"
                size="mini"
                type="danger"
                icon="el-icon-delete"
              >删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <el-pagination
        :background="true"
        :pager-count="5"
        :current-page="page"
        :page-size="limit"
        layout="prev, pager, next"
        :total="total"
        @current-change="changePage"
      >
      </el-pagination>
      <!-- 提示对话框 -->
      <el-dialog
        :title="ruleForm.id?'修改品牌':'添加品牌'"
        :visible.sync="dialogVisible"
        width="30%">
        <!-- 内容 -->
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="品牌名称" prop="tmName">
            <el-input v-model="ruleForm.tmName"></el-input>
          </el-form-item>
          <el-form-item label="品牌LOGO" prop="logoUrl">
            <el-upload
              class="avatar-uploader"
              action="http://gmall-h5-api.atguigu.cn/admin/product/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload">
              <img v-if="ruleForm.logoUrl" :src="ruleForm.logoUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addTrademarkItem">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import {
  reqAddTrademarkItemAsync,
  reqGetTrademarkListAsync,
  reqRemoveTrademarkItemAsync,
  reqUpDataTrademarkItemAsync
} from '@/api/trademark'

export default {
  name: 'Trademark',
  data() {
    return {
      trademarkList: [], // 品牌初始数据
      page: 1, // 初始页
      limit: 3, // 初始每页数据
      total: 10, // 初始总条数
      pages: 10, // 初始总页数
      dialogVisible: false, // 对话框初始默认不显示
      ruleForm: { // 收集表单信息
        tmName: '',
        logoUrl: ''
      },
      rules: { // 表单校验规则
        tmName: [
          { required: true, message: '请输入品牌名称', trigger: 'blur' }
        ],
        logoUrl: [
          { required: true, message: '请上传品牌图片', trigger: 'change' }
        ]
      }
    }
  },
  mounted() {
    // 初始化获取品牌数据
    this.getTrademarkList()
  },
  methods: {
    // 获取品牌数据
    async getTrademarkList() {
      try {
        const result = await reqGetTrademarkListAsync(this.page, this.limit)
        this.total = result.data.total
        this.pages = result.data.pages
        this.trademarkList = result.data.records
      } catch (e) {
        this.$message.error('获取品牌数据失败')
      }
    },
    // 页码的改变
    changePage(currentPage) {
      this.page = currentPage
      // 初始化获取品牌数据
      this.getTrademarkList()
    },
    // 点击显示对话框
    isDialog() {
      // 显示对话框
      this.dialogVisible = true
      // 清空上一个添加的表单数据
      this.ruleForm = {
        tmName: '',
        logoUrl: ''
      }
      // 清除表单验证
      this.$refs['ruleForm']?.clearValidate()
    },
    // 图片上传成功的回调
    handleAvatarSuccess(res) {
      this.ruleForm.logoUrl = res.data
    },
    // 图片上传时的校验
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt5M = file.size / 1024 / 1024 / 1024 / 1024 / 1024 <= 5

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt5M) {
        this.$message.error('上传头像图片大小不能超过 5MB!')
      }
      return isJPG && isLt5M
    },
    // 添加/修改品牌功能
    addTrademarkItem() {
      // 表单的整体校验
      this.$refs['ruleForm'].validate(async(valid) => {
        if (!valid) { // 校验失败
          return false
        } else { // 校验成功
          try {
            if (this.ruleForm.id) { // 代表是修改功能
              await reqUpDataTrademarkItemAsync(this.ruleForm)
              this.$message.success('修改品牌数据成功')
              // 更新数据
              await this.getTrademarkList()
            } else { // 代表是添加功能
              await reqAddTrademarkItemAsync(this.ruleForm)
              this.$message.success('添加品牌数据成功')
              // 更新数据
              await this.getTrademarkList()
            }
          } catch (e) {
            this.$message.error(this.ruleForm.id ? '修改数据失败' : '添加数据失败')
          }
          // 隐藏对话框
          this.dialogVisible = false
        }
      })
    },
    // 修改功能
    upDataTrademarkItem(item) {
      // 显示对话框
      this.dialogVisible = true
      // 获取需要修改的数据
      this.ruleForm = { ...item }
    },
    // 删除功能
    async removeTrademarkItem(id) {
      try {
        await reqRemoveTrademarkItemAsync(id)
        this.$message.success('删除品牌数据成功')
        // 更新数据
        await this.getTrademarkList()
      } catch (e) {
        this.$message.error('删除品牌数据失败')
      }
    }
  }
}
</script>

<style scoped lang="scss">
.box-card{
  margin: 20px 0px 0 20px;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
